package com.atguigu.tingshu.payment.api;

import com.atguigu.tingshu.common.login.TsLogin;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.atguigu.tingshu.payment.service.WxPayService;
import com.wechat.pay.java.service.payments.model.Transaction;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Tag(name = "微信支付接口")
@RestController
@RequestMapping("api/payment/wxPay")
@Slf4j
public class WxPayApiController {

    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private PaymentInfoService paymentInfoService;


    @Operation(summary = "异步回调")
    @PostMapping("/notify")
    public Result wxnotify(HttpServletRequest request) {
        System.out.println("异步回调！");
        Transaction transaction =  wxPayService.wxNotify(request);
        Map<String, Object> result = new HashMap<>();
        if (null!= result){
            if (transaction.getTradeState().equals(Transaction.TradeStateEnum.SUCCESS)){
                paymentInfoService.updatePaymentStatus(transaction);
                result.put("code","SUCCESS");
                result.put("message","成功");
                return Result.ok(result);
            }
        }
        result.put("code","FAIL");
        result.put("message","失败");

        return Result.ok(result);
    }


    @Operation(summary = "查看订单支付状态")
    @GetMapping("/queryPayStatus/{orderNo}")
    public Result queryPayStatus(@PathVariable String orderNo) {
        Transaction result = wxPayService.queryPayStatus(orderNo);
        if (null != result) {
            if (result.getTradeState().equals(Transaction.TradeStateEnum.SUCCESS)) {

                paymentInfoService.updatePaymentStatus(result);

                return Result.ok(true);
            }
        }
        return Result.ok(false);


    }


    @TsLogin
    @Operation(summary = "微信支付")
    @PostMapping("/createJsapi/{paymentType}/{orderNo}")
    public Result createJsapi(@PathVariable String orderNo,
                              @PathVariable String paymentType) {
        Long userId = AuthContextHolder.getUserId();
        Map<String, Object> map = wxPayService.createJsapi(orderNo, paymentType, userId);
        return Result.ok();


    }
}

